package shiro.com.controller.login;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import shiro.com.basie.domain.Result;
import shiro.com.domain.sys.SysUsers;
import shiro.com.domain.sys.vo.PermissionListVo;
import shiro.com.service.sys.ISysUsersService;
import shiro.com.service.sys.ISysResoureTestService;
import shiro.com.utils.shiro.token.JwtToken;
import shiro.com.utils.shiro.util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


@RestController
@CrossOrigin
@Api(tags="登录")
@ApiModel("登录")
public class Test {

    @Autowired
    private  ISysUsersService sysUsersService;
    @Autowired
    private ISysResoureTestService sysResoureTestService;

    @PostMapping(value = "/loginin")
    public String getInfo(@RequestBody SysUsers sysUsers)
    {
        if (sysUsers.getSysUserPsw().isEmpty()){
            return JSON.toJSONString(new Result().setCode(500).setMessage("用户名密码错误"));
        }
        Subject subject = SecurityUtils.getSubject();
        String jwt = JwtUtil.createJWT(sysUsers.getSysUserName(),"back","user",1000*60*30);
        JwtToken jwtToken = new JwtToken(jwt,sysUsers.getSysUserPsw());
        try{
            subject.login(jwtToken);
        }catch (UnknownAccountException e){
            return JSON.toJSONString(new Result().setCode(401).setMessage("账号不存在"));
        }catch (IncorrectCredentialsException e){
            return JSON.toJSONString(new Result().setCode(401).setMessage("密码错误"));

        }

        SysUsers backUser = sysUsersService.selectByUsername(sysUsers.getSysUserName());
        List<PermissionListVo> mapList = sysResoureTestService.selectSysResoureRoleList(backUser.getSysUserName());
        Set<String> btn = sysResoureTestService.selectSysResoureTestByUserName(backUser.getSysUserName());
        backUser.setSysUserPsw(null);
        backUser.setSysUserSlat(null);

        Map<String,Object> map = new HashMap<String,Object>();

        map.put("sysUsers",backUser);
        map.put("token",jwt);
        map.put("permissionlist",mapList);
        map.put("btnPre",btn);
        return JSON.toJSONString(new Result().setCode(200).setMessage("登录成功").setData(map));

    }


    @GetMapping("/loginout")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return new Result().setCode(200).setMessage("成功退出");
    }


}
